package cn.cxyxj.study110;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

//@Component
public class MyAccess {
// 只需要登录就能访问的接口地址
    private static final Set<String> URL = new HashSet<>();
 // 需要区分角色的接口地址  用户名称：接口地址
    private static final HashMap<String,Set<String>> URL_MAP = new HashMap();
    static {
        URL.add("/hello");

        Set<String> cxyxjSet = new HashSet<>();
        cxyxjSet.add("/cxyxj/hello");
        cxyxjSet.add("/security/hello");
        URL_MAP.put("cxyxj",cxyxjSet);
        
        Set<String> securitySet = new HashSet<>();
        securitySet.add("/security/hello");
        URL_MAP.put("security",securitySet);
    }

   public boolean hasPermit(HttpServletRequest req, Authentication auth){
       Object principal = auth.getPrincipal();
       // 如果为匿名用户，则直接返回 false
       if(principal.toString().equals("anonymousUser")){
           return false;
       }
       String servletPath = req.getRequestURI();
       AntPathMatcher matcher = new AntPathMatcher();
       // 有一些接口是不需要权限，只要登录就能访问的，比如一些省市区接口
       boolean result = URL.stream().anyMatch(url -> matcher.match(url, servletPath));
       if(result){
           return true;
       }
       //这里使用的是定义在内存的用户信息
       if(principal instanceof User){
           User user = (User) principal;
           // 可以根据用户id或者用户名从redis中获得用户拥有的菜单权限url
           String username = user.getUsername();
           Set<String> urlSet = URL_MAP.get(username);
           return urlSet.stream().anyMatch(u -> matcher.match(u, servletPath));
       }
       return false;
   }

}